package com.googlecode.cswish.util;

import java.util.ArrayList;

/**
 * Auto create
 * 
 * @author jerry.feng
 * 
 */
public class SafeArrayList<E> extends ArrayList<E> {

	// avoid performance problem because of wrong big index
	private int safeCreateSize = 100;
	
	private NewInstance<E> callback;
	
	public SafeArrayList(NewInstance<E> callback) {
		this.callback = callback;
	}
	
	public SafeArrayList(NewInstance<E> callback, int safeCreateSize) {
		this.callback = callback;
		this.safeCreateSize = safeCreateSize;
	}
	
	public E get(int index) {
		int step = size() - index;
		if (step <= 0 && -step < safeCreateSize) {
			while (step++ <= 0) {
				add(callback.create());
			}
		}
		
		return super.get(index);
	}
	
	public interface NewInstance<E> {
		E create();
	}
}